var CurrentUser;    //Global variable

function getName() {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    CurrentUser = user;   //global variable
    if (user) {
        console.log("Currently logged in:  " + user["name"]);
        document.getElementById("name-goes-here").innerText = user["name"];
    } else {
        console.log("No one is logged in");
    }
}
getName(); //run the function


function populateHistory() {
    // find out who is logged in 
    var who = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    let email = who["email"];
    const user = users.find(u => u.email === email);
    // get information for that user who is logged in
    if (user) {
        historyArray = user["history"];
        historyArray.forEach((hist, index) => {
            let historyCardTemplate = document.getElementById("postCardTemplate");
            let historyCardGroup = document.getElementById("history-goes-here");
            let onecard = historyCardTemplate.content.cloneNode(true);
            onecard.querySelector(".date").innerHTML = hist.date;
            onecard.querySelector(".count").innerHTML = hist.calories;
            onecard.querySelector(".card-description").innerHTML = hist.details;
            onecard.querySelector('.card-image').src = " ./images/" + hist.imageName;
            onecard.querySelector('.deleteButton').onclick = () => deleteHistory(index);
            onecard.querySelector('.editButton').onclick = () => editHistory(index);

            historyCardGroup.appendChild(onecard);
            
        })

    } else {
        console.log("No one is logged in");
    }
}
populateHistory();

function deleteHistory(id) {
    var users = JSON.parse(localStorage.getItem("users"));
    const user = users.find(u => u.email === CurrentUser["email"]);
    // Get a confirmation from User before you delete
    if (confirm("Are you sure you want to delete this history: " + user.history[id].details +
        " on " + user.history[id].date)) {

        user.count=Number(user.count)-Number(user.history[id].calories);
        // remove this item from array at index position "id"
        user.history.splice(id,1);
        localStorage.setItem("users", JSON.stringify(users));
        alert('History data deleted successfully!');
        location.reload();
    }
}
function editHistory(id) {
    const parameters=new URLSearchParams();
    parameters.append("id", id);
    location.href = "../Calorie.html?" + parameters.toString();
}